package com.appspot.diasporajava.federation;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Category;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Link;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pegdown.Extensions;
import org.pegdown.LinkRenderer;
import org.pegdown.PegDownProcessor;
import org.pegdown.ToHtmlSerializer;
import org.pegdown.ast.RootNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tautua.markdownpapers.Markdown;
import org.tautua.markdownpapers.parser.ParseException;

import com.appspot.diasporajava.controller.MainController;
import com.appspot.diasporajava.util.WebsiteVisitor;
import com.petebevin.markdown.MarkdownProcessor;

@Component
public class PublicFeed {
	private Log log = LogFactory.getLog(MainController.class);

	@Autowired
	WebsiteVisitor websiteVisitor;

	MarkdownProcessor m = new MarkdownProcessor();

	public static void main(String[] args) {
		AbderaClient client = new AbderaClient(Abdera.getInstance());
		ClientResponse response = client.get("https://joindiaspora.com/public/apolonisaphrodisia.atom");
		Document<Feed> doc = response.getDocument();
		Feed feed = doc.getRoot();
		// Get the feed title
		System.out.println("Feed Title: " + feed.getTitle());

		// Get the entry items...
		for (Entry entry : feed.getEntries()) {
			System.out.println("Title: " + entry.getTitle());
			System.out.println("Unique Identifier: " + entry.getId().toString());
			System.out.println("Updated Date: " + entry.getUpdated().toString());
			System.out.println("Published Date: " + entry.getPublished());
			System.out.println("Content: " + entry.getContent());

			// Get the links
			for (Link link : (List<Link>) entry.getLinks()) {
				System.out.println("Link: " + link.getHref());
			}

			// Get the categories
			for (Category category : (List<Category>) entry.getCategories()) {
				System.out.println("Category: " + category.getTerm());
			}

		}

	}

	public List<Entry> getEntryList(String atomFeedUrl) {
		Parser parser = new Abdera().getInstance().getParser();
		Document<Feed> doc = parser.parse(websiteVisitor.getInputStream(atomFeedUrl));
		Feed feed = doc.getRoot();

		return feed.getEntries();
	}

	public List<Entry> getContentList(String getEntryList) {
		List<Entry> entries = getEntryList(getEntryList);
		List<String> contentList = new ArrayList<String>();
		
		for(Entry entry:entries){
			entry.setContent(transformMarkdownJ(entry.getContent()));
		}

		return entries;
	}

	public String transformPapers(String string) {
		Reader in = new StringReader(string);
		StringWriter out = new StringWriter();

		Markdown md = new Markdown();
		try {
			md.transform(in, out);
			return out.getBuffer().toString();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public String transformMarkdownJ(String string) {
		string.replaceAll("#", "&#35;");
		if (string.lastIndexOf("![t]") > 0) {
			string= transformNestedImages(string);
		} 

		//String result=string;
		String result = m.markdown(string);
		
		result=result.replaceAll("<h1>", "#");
		result=result.replaceAll("</h1>", "");

		log.debug(result);

		return result;
	}

	public String transform(String string) {
		PegDownProcessor processor = new PegDownProcessor(Extensions.ALL);
		// return processor.markdownToHtml(string);
		LinkRenderer linkRenderer = new LinkRenderer();

		RootNode astRoot = processor.parseMarkdown(string.toCharArray());
		ToHtmlSerializer serializer = new HtmlSerializer(linkRenderer);
		String result = serializer.toHtml(astRoot);
		if (result.lastIndexOf("![t]") > 0) {
			return transformNestedImages(result);
		} else {
			return result;
		}
	}

	private String transformNestedImages(String string) {
		StringBuffer stringBuffer = new StringBuffer();
		String[] images = string.split("\\[ !\\[t\\]");
		for (String image : images) {
			String[] pieces = image.split("\"");
			if (pieces.length == 1)
				stringBuffer.append(image);
			else if (pieces.length >= 4)
				stringBuffer.append("<a href='" + pieces[3] + "'><img src='" + pieces[1] + "'></img></a>");
			else
				stringBuffer.append("<a href='" + pieces[1] + "'><img src='" + pieces[1] + "'></img></a>");
		}
		return stringBuffer.toString();
	}
}
